# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '2190': {  # zs [微信3.2,支付宝2.5], [微信D1,支付宝D0], [微信限额: 20|30|50|100|200|300|500,支付宝：10-1w]
        'API_KEY': 'a42956bf47944e4a811efb87a9a82a61',
        'gateway': 'http://pay.tingniangjj.cn/chargebank.aspx',
        'query_gateway': 'http://pay.tingniangjj.cn/search.aspx',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(s):
    m = hashlib.md5()
    m.update(s.encode('GB2312'))
    sign = m.hexdigest()
    return sign


def gen_sign(d, key):
    s = 'parter={}&type={}&value={}&orderid={}&callbackurl={}{}'.format(
        d['parter'], d['type'], d['value'], d['orderid'], d['callbackurl'], key)
    return generate_sign(s)


def calc_sign(d, key):
    s = 'orderid={}&opstate={}&ovalue={}{}'.format(
        d['orderid'], d['opstate'], d['ovalue'], key)
    return generate_sign(s)


def search_sign(d, key):
    s = 'orderid={}&parter={}{}'.format(
        d['orderid'], d['parter'], key)
    return generate_sign(s)


def verify_notify_sign(params, key):
    sign = params.pop('sign')
    calculated_sign = calc_sign(params, key)
    if sign.lower() != calculated_sign.lower():
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    """
    微信WAP 1005
    支付宝WAP 1006
    """
    if service == 'wxpay':
        payType = '1005'
    elif service == 'alipay':
        payType = '1006'
    return payType


def _build_query_string(d):
    s = ''
    for k in d.keys():
        s += '%s=%s&' % (k, d[k])
    return s[:-1]


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info['service']
    parameter_dict = OrderedDict((
        ('parter', app_id),
        ('type', _get_pay_type(service)),
        ('value', str(int(pay_amount))),
        ('orderid', str(pay.id)),
        ('callbackurl', '{}/pay/api/{}/shuntingpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameter_dict['sign'] = gen_sign(parameter_dict, api_key)
    data = json.dumps(parameter_dict)
    url = _get_gateway(app_id) + '?' + _build_query_string(parameter_dict)
    _LOGGER.info("shuntingpay create: url: %s, %s", url, data)
    return {'charge_info': url}


# opstate=0 表示成功
def check_notify_sign(request, app_id):
    data = dict(request.GET.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("shuntingpay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['orderid']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('shuntingpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id  # 商户编号
    trade_status = str(data['opstate'])
    trade_no = data['sysorderid']
    total_fee = float(data['ovalue'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == '0':
        _LOGGER.info('shuntingpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)

    data = OrderedDict((
        ('orderid', str(pay_id)),  # 订单号
        ('parter', app_id),  # 商户号
    ))
    data['Sign'] = search_sign(data, api_key)

    url = _get_query_gateway(app_id) + '?' + _build_query_string(data)
    _LOGGER.info(u'shuntingpay query: %s', url)
    response = requests.get(url, verify=False)
    _LOGGER.info(u'shuntingpay query rsp: %s', response.text)

    if response.status_code == 200:
        s = response.text
        trade_status = _get_str(s, 'opstate=', '&')  # 0:支付成功, 1:商户订单号无效, 2:签名错误, 3:请求参数无效
        total_fee = float(_get_str(s, 'ovalue=', '&'))
        trade_no = pay_order.id
        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee
        }

        if trade_status == '0':
            check_channel_order(pay_id, total_fee, app_id)
            _LOGGER.info('shuntingpay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('shuntingpay data error, status_code: %s', response.status_code)


def _get_str(s, start, end):
    p1 = s.index(start)
    p2 = s.index(end, p1 + len(start))
    if p2 > p1:
        return s[p1 + len(start): p2]
    else:
        return ''
